package com.macro.mall.portal.service.impl;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.macro.mall.common.exception.Assert;
import com.macro.mall.mgb.mapper.MemberMapper;
import com.macro.mall.mgb.model.Member;
import com.macro.mall.portal.domain.MemberDetails;
import com.macro.mall.portal.service.MemberService;
import com.macro.mall.portal.service.UmsMemberCacheService;
import com.macro.mall.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;


/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author wangwang
 * @since 2025-07-18
 */
@Service
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UmsMemberCacheService umsMemberCacheService;

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public String getAuthCode(String telephone) {
        boolean isPhone = Validator.isMobile(telephone);
        if (!isPhone) {
            Assert.fail("手机号格式错误");
        }
        //生成验证码
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        String authCode = code.toString();
        //将验证码存入redis中
        umsMemberCacheService.setAuthCode(telephone, authCode);
        log.debug("发送验证码成功,验证码：{}", authCode);
        return authCode;
    }

    @Override
    @Transactional
    public void register(String username, String password, String telephone, String authCode) {
        String code = umsMemberCacheService.getAuthCode(telephone);
        if (code == null || !code.equals(authCode)) {
            Assert.fail("验证码错误");
        }
        Member member = query().eq("phone", telephone).one();
        if (member != null) {
            Assert.fail("用户已存在");
        }
        Member user = query().eq("username", username).one();
        if (user != null) {
            Assert.fail("用户名已经存在，请重新输入");
        }
        Member newMember = new Member();
        newMember.setUsername(username);
        newMember.setPhone(telephone);
        newMember.setPassword(passwordEncoder.encode(password));
        newMember.setStatus(1);
        newMember.setNickname(username);
        //设置默认会员等级
        newMember.setMemberLevelId(4L);
        save(newMember);
        log.debug("注册成功");
        newMember.setPassword(null);
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码错误");
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            log.error("登录异常：{}", e.getMessage());
        }
        return token;
    }

    @Override
    public Member getCurrentMember() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        MemberDetails memberDetails = (MemberDetails) authentication.getPrincipal();
        return memberDetails.getMember();
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        Member member = getByUsername(username);
        if (member != null) {
            return new MemberDetails(member);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @Override
    public String refreshToken(String token) {
        return jwtTokenUtil.refreshHeadToken(token);
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        Member record = new Member();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateById(record);
        umsMemberCacheService.delMember(id);
    }

    private Member getByUsername(String username) {
        Member member = umsMemberCacheService.getMember(username);
        if (member == null) {
            Member user = query().eq("username", username).one();
            if (user == null) {
                Assert.fail("该用户不存在，请先注册");
            }
            umsMemberCacheService.setMember(user);
            return user;
        }
        return member;
    }
}
